import 'package:get/get.dart';
import '../../../data/services/alarm_service.dart';
import '../../home/controllers/home_controller.dart';

class MessageController extends GetxController {
  // 服务实例 - GetX规范
  final AlarmService _alarmService = Get.find<AlarmService>();

  // 响应式变量
  final selectedTabIndex = 0.obs;
  final isLoading = false.obs;
  final unreadCount = 0.obs;
  final alarmTypes = <Map<String, dynamic>>[].obs;
  final messageList = <Map<String, dynamic>>[].obs;
  final channelMessages = <Map<String, dynamic>>[].obs;

  // 分页相关
  final currentPage = 1.obs;
  final pageSize = 10.obs;
  final hasMoreData = true.obs;
  final totalCount = 0.obs;

  // 过滤条件
  final readStatusFilter = Rxn<int>(); // null=全部, 0=未读, 1=已读
  final selectedDate = DateTime.now().obs; // 选择的日期
  final isDateFilterEnabled = false.obs; // 是否启用日期筛选

  @override
  void onReady() {
    super.onReady();
    // 页面准备好后初始化数据
    _initData();
  }

  /// 初始化数据
  Future<void> _initData() async {
    // 初始化时根据默认选中的tab设置readStatus过滤条件
    _setReadStatusForCurrentTab();

    await Future.wait([
      _loadAlarmTypes(),
      _loadUnreadCount(),
      _loadMessageList(),
      _loadChannelMessages(),
    ]);
  }

  /// 根据当前选中的tab设置readStatus过滤条件
  void _setReadStatusForCurrentTab() {
    switch (selectedTabIndex.value) {
      case 0:
        // 告警消息tab - 获取全部消息（不传readStatus）
        readStatusFilter.value = null;
        break;
      case 1:
        // 未读消息tab - 只获取未读消息（readStatus: 0）
        readStatusFilter.value = 0;
        break;
      default:
        readStatusFilter.value = null;
        break;
    }
  }

  /// 切换标签
  void changeTab(int index) {
    print('🔄 切换Tab到: $index (0=告警消息, 1=未读消息)');
    selectedTabIndex.value = index;

    // 根据新选中的tab设置readStatus过滤条件
    _setReadStatusForCurrentTab();

    // 切换标签时刷新数据
    _refreshMessageList();
  }

  /// 获取告警类型
  Future<void> _loadAlarmTypes() async {
    try {
      final response = await _alarmService.getAlarmTypes();
      final data = response['data'] as List<dynamic>?;
      if (data != null) {
        alarmTypes.value = data.cast<Map<String, dynamic>>();
        print('获取告警类型成功：${alarmTypes.length}个类型');
      }
    } catch (e) {
      print('获取告警类型失败: $e');
    }
  }

  /// 获取未读消息数
  Future<void> _loadUnreadCount() async {
    try {
      // ✅ 根据日期筛选状态设置时间范围
      String? startAt;
      String? endAt;

      if (isDateFilterEnabled.value) {
        // 如果启用了日期筛选，设置当天的开始和结束时间（本地时间）
        final date = selectedDate.value;
        final startTime = DateTime(date.year, date.month, date.day);
        final endTime = DateTime(date.year, date.month, date.day, 23, 59, 59);

        // ✅ 修复：后端接口期望本地时间，不转换为UTC时间
        // 使用接口要求的格式：YYYY-MM-DD HH:mm:ss（空格分隔，不是T）
        startAt = _formatDateTimeForUnreadAPI(startTime);
        endAt = _formatDateTimeForUnreadAPI(endTime);

        print('📅 未读数查询使用日期筛选 (本地时间): $startAt ~ $endAt');
      }

      final response = await _alarmService.getUnreadAlarmCount(
        startAt: startAt,
        endAt: endAt,
      );
      final data = response['data'] as int?;
      if (data != null) {
        unreadCount.value = data;
        print(
          '获取未读消息数成功：$data${startAt != null ? ' (时间范围: $startAt ~ $endAt)' : ''}',
        );
      }
    } catch (e) {
      print('获取未读消息数失败: $e');
    }
  }

  /// 刷新未读消息数（公共方法，供其他Controller调用）
  Future<void> refreshUnreadCount() async {
    try {
      await _loadUnreadCount();
      print('✅ 刷新未读消息数完成: ${unreadCount.value}');
    } catch (e) {
      print('⚠️ 刷新未读消息数失败: $e');
    }
  }

  /// 获取消息列表
  Future<void> _loadMessageList({bool isRefresh = false}) async {
    if (isLoading.value) return;

    try {
      isLoading.value = true;
      print(
        '📥 加载消息列表 - 刷新:$isRefresh, 页码:${currentPage.value}, 筛选:${readStatusFilter.value}',
      );

      if (isRefresh) {
        currentPage.value = 1;
        hasMoreData.value = true;
      }

      // 根据日期筛选状态设置时间范围
      String? startAt;
      String? endAt;

      if (isDateFilterEnabled.value) {
        // 如果启用了日期筛选，设置当天的开始和结束时间（本地时间）
        final date = selectedDate.value;
        final startTime = DateTime(date.year, date.month, date.day);
        final endTime = DateTime(date.year, date.month, date.day, 23, 59, 59);

        // 转换为UTC时间再发送给后端
        final startTimeUtc = startTime.toUtc();
        final endTimeUtc = endTime.toUtc();

        startAt = _formatDateTimeForAPI(startTimeUtc);
        endAt = _formatDateTimeForAPI(endTimeUtc);

        print(
          '📅 使用日期筛选 (本地时间): ${_formatDateTimeForAPI(startTime)} ~ ${_formatDateTimeForAPI(endTime)}',
        );
        print('📅 转换为UTC时间: $startAt ~ $endAt');
      }

      final response = await _alarmService.getAlarmMessages(
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        readStatus: readStatusFilter.value,
        startTime: startAt,
        endTime: endAt,
      );

      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        final records = data['records'] as List<dynamic>? ?? [];
        final total = data['total'] as int? ?? 0;
        final pages = data['pages'] as int? ?? 0;

        totalCount.value = total;

        // 转换为Map格式
        final newMessages = records.cast<Map<String, dynamic>>();

        if (isRefresh) {
          // 刷新时直接替换
          final uniqueMessages = _removeDuplicateMessages(newMessages);
          print(
            '🔄 刷新模式 - 新消息:${newMessages.length}条, 去重后:${uniqueMessages.length}条',
          );
          messageList.value = uniqueMessages;
          messageList.refresh(); // ✅ 显式触发响应式更新
          print('✅ 列表更新完成 - 当前列表长度:${messageList.length}');
        } else {
          // 加载更多时去重合并
          final combinedMessages = [...messageList, ...newMessages];
          final uniqueMessages = _removeDuplicateMessages(combinedMessages);
          print(
            '📚 加载更多 - 原有:${messageList.length}条, 新增:${newMessages.length}条, 去重后:${uniqueMessages.length}条',
          );
          messageList.value = uniqueMessages;
          messageList.refresh(); // ✅ 显式触发响应式更新
          print('✅ 列表更新完成 - 当前列表长度:${messageList.length}');
        }

        // 检查是否还有更多数据
        hasMoreData.value = currentPage.value < pages;

        print(
          '✅ 获取消息列表成功：当前页${currentPage.value}，总数$total，列表实际数量${messageList.length}',
        );
      }
    } catch (e) {
      print('获取消息列表失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 去除重复消息（根据消息ID去重）
  List<Map<String, dynamic>> _removeDuplicateMessages(
    List<Map<String, dynamic>> messages,
  ) {
    final seenIds = <String>{};
    final uniqueMessages = <Map<String, dynamic>>[];

    for (final message in messages) {
      final id = message['id']?.toString();
      if (id != null && !seenIds.contains(id)) {
        seenIds.add(id);
        uniqueMessages.add(message);
      }
    }

    return uniqueMessages;
  }

  /// 获取按通道分组的消息
  Future<void> _loadChannelMessages() async {
    try {
      final response = await _alarmService.getChannelAlarmMessages();
      final data = response['data'] as List<dynamic>?;
      if (data != null) {
        channelMessages.value = data.cast<Map<String, dynamic>>();
        print('获取通道消息成功：${channelMessages.length}个通道');
      }
    } catch (e) {
      print('获取通道消息失败: $e');
    }
  }

  /// 刷新消息列表
  Future<void> _refreshMessageList() async {
    print('📱 开始刷新消息列表...');
    await _loadMessageList(isRefresh: true);
    await _loadUnreadCount(); // 同时刷新未读数
    print('✅ 消息列表刷新完成，当前消息数：${messageList.length}');
  }

  /// 加载更多消息
  Future<void> loadMoreMessages() async {
    if (!hasMoreData.value || isLoading.value) return;

    currentPage.value++;
    await _loadMessageList();
  }

  /// 标记消息已读
  Future<void> markMessageRead(
    String msgId,
    String hsId, {
    String? deviceId,
  }) async {
    try {
      // ✅ 统一传递deviceId参数，与设备详情页面保持一致
      await _alarmService.markAlarmMessageRead(
        msgId: msgId,
        hsId: hsId,
        deviceId: deviceId != null && deviceId.isNotEmpty ? deviceId : null,
      );

      // 优化：先更新本地状态，再异步刷新
      _updateLocalMessageReadStatus(msgId);

      // 异步刷新未读数，避免重复请求消息列表
      _loadUnreadCount();

      // 刷新首页未读消息数
      if (Get.isRegistered<HomeController>()) {
        final homeController = Get.find<HomeController>();
        homeController.refreshUnreadCount();
      }

      print('消息标记已读成功');
    } catch (e) {
      print('标记消息已读失败: $e');
      // 失败时重新加载消息列表
      _refreshMessageList();
    }
  }

  /// 更新本地消息的已读状态
  void _updateLocalMessageReadStatus(String msgId) {
    final messageIndex = messageList.indexWhere(
      (message) => message['id']?.toString() == msgId,
    );

    if (messageIndex >= 0) {
      // 如果当前在未读消息tab，直接移除该消息
      if (selectedTabIndex.value == 1) {
        final newList = List<Map<String, dynamic>>.from(messageList);
        newList.removeAt(messageIndex);
        messageList.value = newList;
      } else {
        // 否则只更新状态
        final newList = List<Map<String, dynamic>>.from(messageList);
        newList[messageIndex] = {
          ...newList[messageIndex],
          'readStatus': 1,
          'read': true,
        };
        messageList.value = newList;
      }

      // 更新未读数量
      if (unreadCount.value > 0) {
        unreadCount.value = unreadCount.value - 1;
      }

      print('本地更新消息状态成功: $msgId');
    }
  }

  /// 一键已读（标记所有消息为已读）
  Future<void> markAllMessagesRead() async {
    if (isLoading.value) return; // 防止重复操作

    try {
      isLoading.value = true;
      print(
        '📖 开始执行一键已读，当前Tab: ${selectedTabIndex.value}, 当前消息数: ${messageList.length}',
      );

      // ✅ 如果启用了日期筛选，传递 readDay 参数
      String? readDay;
      if (isDateFilterEnabled.value) {
        final date = selectedDate.value;
        readDay =
            '${date.year.toString().padLeft(4, '0')}-'
            '${date.month.toString().padLeft(2, '0')}-'
            '${date.day.toString().padLeft(2, '0')}';
        print('📅 使用日期筛选，readDay: $readDay');
      }

      // 使用新的一键已读API
      await _alarmService.markAllMessagesRead(readDay: readDay);

      // 优化：先更新本地状态，减少网络请求
      _updateAllLocalMessagesReadStatus();

      // 异步刷新未读数
      _loadUnreadCount();

      // 刷新首页未读消息数
      if (Get.isRegistered<HomeController>()) {
        final homeController = Get.find<HomeController>();
        homeController.refreshUnreadCount();
      }

      print('✅ 一键已读成功，处理后消息数: ${messageList.length}');
    } catch (e) {
      print('❌ 一键已读失败: $e');
      // 失败时重新加载数据
      _refreshMessageList();
    } finally {
      isLoading.value = false;
    }
  }

  /// 更新所有本地消息为已读状态
  void _updateAllLocalMessagesReadStatus() {
    // 如果当前在未读消息tab，直接清空列表
    if (selectedTabIndex.value == 1) {
      messageList.value = [];
      print('清空未读消息列表，当前消息数：${messageList.length}');
    } else {
      // 否则更新所有消息的状态
      final updatedMessages =
          messageList.map((message) {
            return {...message, 'readStatus': 1, 'read': true};
          }).toList();
      messageList.value = updatedMessages;
    }

    // 将未读数量设置为0
    unreadCount.value = 0;

    print('本地批量更新消息状态完成');
  }

  /// 设置已读状态过滤
  void setReadStatusFilter(int? readStatus) {
    readStatusFilter.value = readStatus;
    _refreshMessageList();
  }

  /// 获取全部消息
  void showAllMessages() {
    setReadStatusFilter(null);
  }

  /// 获取未读消息
  void showUnreadMessages() {
    setReadStatusFilter(0);
  }

  /// 获取已读消息
  void showReadMessages() {
    setReadStatusFilter(1);
  }

  /// 手动刷新
  Future<void> refreshData() async {
    await _initData();
  }

  /// 刷新消息列表（公共方法，供视图调用）
  Future<void> refreshMessageList() async {
    await _refreshMessageList();
  }

  /// 设置日期筛选
  void setDateFilter(DateTime date) {
    selectedDate.value = date;
    isDateFilterEnabled.value = true;
    _refreshMessageList();
  }

  /// 清除日期筛选
  void clearDateFilter() {
    isDateFilterEnabled.value = false;
    _refreshMessageList();
  }

  /// 格式化日期时间为API需要的格式（ISO 8601: YYYY-MM-DDTHH:mm:ss）
  String _formatDateTimeForAPI(DateTime dateTime) {
    return '${dateTime.year.toString().padLeft(4, '0')}-'
        '${dateTime.month.toString().padLeft(2, '0')}-'
        '${dateTime.day.toString().padLeft(2, '0')}T'
        '${dateTime.hour.toString().padLeft(2, '0')}:'
        '${dateTime.minute.toString().padLeft(2, '0')}:'
        '${dateTime.second.toString().padLeft(2, '0')}';
  }

  /// 格式化日期时间为未读消息数API需要的格式（YYYY-MM-DD HH:mm:ss，空格分隔）
  String _formatDateTimeForUnreadAPI(DateTime dateTime) {
    return '${dateTime.year.toString().padLeft(4, '0')}-'
        '${dateTime.month.toString().padLeft(2, '0')}-'
        '${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:'
        '${dateTime.minute.toString().padLeft(2, '0')}:'
        '${dateTime.second.toString().padLeft(2, '0')}';
  }
}
